package com.qjc.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 国际化提示处理工具
 *
 * @ClassName: MessageUtils
 * @Author: qjc
 * @Date: 2022/12/28 10:23
 */

@Slf4j
@Component
public class MessageUtils {

    private static MessageSource messageSource;


    public MessageUtils(MessageSource messageSource) {
        if (log.isInfoEnabled()) {
            log.info("MessageUtils construction success");
        }
        MessageUtils.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            return messageSource.getMessage(msgKey, null, locale);
        } catch (Exception e) {
            log.error("msgKey:{},locale:{},MessageUtils.get Exception:{}", msgKey, locale, e.getMessage());
            return null;
        }
    }

    /**
     * 获取指定语言的单个国际化翻译值
     */
    public static String get(String msgKey, String language) {
        try {
            Locale locale = new Locale(language);
            if (log.isInfoEnabled()) {
                log.info("get,msgKey:{},language:{},locale:{}", msgKey, language, locale);
            }
            return messageSource.getMessage(msgKey, null, locale);
        } catch (Exception e) {
            log.error("msgKey:{},language:{},MessageUtils.get Exception:{}", msgKey, language, e.getMessage());
            return messageSource.getMessage(msgKey, null, Locale.ENGLISH);
        }
    }


}
